<?php
class SecurityImage {
	var $image;
	var $width;
	var $height;
	var $num_chars;
	var $num_lines;
	var $spacing;
	var $security_code;
      
	public function __construct($width = 150, $height = 30, $num_chars = 5, $num_lines = 30) {
		$this->width = $width;
		$this->height = $height;
		$this->num_chars = $num_chars;
		$this->num_lines = $num_lines;
 		// create new image
		$this->image = imagecreate($width, $height);
		// allocate white background colour
		imagecolorallocate($this->image, 255, 255, 255);
		// calculate spacing between characters based on width of image
		$this->spacing = (int)($this->width / $this->num_chars);
	}

	public function drawLines() {
		for($i = 0; $i<$this->num_lines; $i++) {
			$random_grey = rand(190, 250);
			$line_color = imagecolorallocate($this->image, $random_grey, $random_grey, $random_grey);
			imageline($this->image, 
				rand(0, $this->width), 
				rand(0, $this->height), 
				rand(0, $this->width), 
				rand(0, $this->height), 
				$line_color
			);
		}
	}

	public function generateCode() {
		// reset code
		$this->security_code = '';
		// loop through and generate the code letter by letter
		for($i = 0; $i<$this->num_chars; $i++) {
			// select random character and add to code string
			$this->security_code .= chr(rand(65, 90));
		}
	}
	
	public function drawCharacters() {
		// loop through and write out selected number of characters
		for($i = 0; $i<strlen($this->security_code); $i++) {
			// select random font
            $current_font = rand(3, 5);
            
            // select random greyscale colour
            $random_red = rand(0, 190);
			$random_green = rand(0, 190);
			$random_blue = rand(0, 190);
            $text_color = imagecolorallocate($this->image, $random_red, $random_green, $random_blue);
            
            // write text to image
            imagestring(
				$this->image, 
				$current_font, 
				$this->spacing/3+$i*$this->spacing, 
				($this->height-imagefontheight($current_font))/2, 
				$this->security_code[$i], 
				$text_color
			);
		}
	}
	
	public function create($file = '') {
		// check for existance of GD GIF library
		if(!function_exists('imagegif')) {
			return false;
		}
		
		$this->drawLines();
		$this->generateCode();
		$this->drawCharacters();
		
		// write out image to file or browser
		if($file!='') {
			// write stream to file
			imagegif($this->image, $file);
		} else {
			// tell browser that data is gif
			header('Content-type: image/gif');
			// write stream to browser
			imagegif($this->image);
		}
		// free memory used in creating image
		imagedestroy($this->image);
		return true;
	}
 
	public function getCode() {
		return $this->security_code;
	}
}
?>
